package com.cjl.demo.data;

/**
 * <p>Description: </p>
 * 二分查找
 * @ uthor chenjinliang
 * @ date: 2020/7/17
 */
public class ErFenSearch {
    public static void main(String[] args) {
        int[] array = {1,2,4,5,6,8,9};
        int key = 10;
        int result = search(array, key, 0, array.length -1);
        System.out.println(result);
    }

    public static int search(int[] array, int key ,int low ,int high){
        if(key < array[low] || key > array[high] || low > high){
            return -1;
        }
        int middle = (low + high) / 2 ;//记录中间位置
        if(array[middle] > key){
            //比较middle左侧区域
            return search(array, key , low, middle - 1);
        }else if(array[middle] < key){
            //比较middle右侧区域
            return search( array, key , middle + 1, high);
        }else{
            return middle;
        }
    }
}
